//当前的页码
var page = 1;
//每页的条数
var count = 8;
//获取tbody
var oTBody = document.querySelector("tbody");
//获取分页容器
var oPagination = document.querySelector(".pagination");
//获取上一页的按钮
var oPrevBtn = document.querySelector(".prev");
//获取下一页的按钮
var oNextBtn = document.querySelector(".next");

//获取编号搜索的输入框
var oSearchIdInp = document.querySelector("#storeShelfId");
//获取库房状态
var oSearchStateInp = document.querySelector("#dropdownMenu1");
//获取搜索按钮
var oSearchBtn = document.querySelector("#search");

//获取添加的保存按钮
var oAddSaveBtn = document.querySelector(".addSaveBtn");
//获取修改的保存
var oEditSaveBtn = document.querySelector(".editSaveBtn");
//获取重置按钮
var oResetBtn = document.querySelector("#reset");

// 左侧导航===========================================================================================
var aA = document.querySelectorAll(".nav>li>a");
var aUl = document.querySelectorAll(".min-nav");
for (var i = 0; i < aA.length; i++) {
    aA[i].onclick = function () {
        var oUl = this.nextElementSibling;
        if (getComputedStyle(oUl).height == "0px") {
            for (var j = 0; j < aUl.length; j++) {
                aUl[j].style.height = "0px";
                aA[j].className = "";
            }
            oUl.style.height =
                oUl.children[0].scrollHeight * oUl.children.length + "px";
            this.className = "active";
        } else {
            oUl.style.height = "0px";
        }
    };
}

// 顶部导航栏隐藏===========================================================================================
var oLeft = document.querySelector(".container-fluid>.left");
var oRight = document.querySelector(".container-fluid>.right");
var oMenu = document.querySelector(".header-left");
oMenu.addEventListener("click", hideDisplayFn);
var flag = true;
function hideDisplayFn() {
    if (flag) {
        oLeft.style.display = "none";
        oRight.style.width = "100%";
        flag = false;
    } else {
        oLeft.style.display = "block";
        oRight.style.width = "calc(100% - 256px)";
        flag = true;
    }
}

// 库房状态============================================================================================
var oDropdown = document.querySelector('.dropdown');
oDropdown.addEventListener('click', changeFn);
function changeFn() {
    // console.log(event.target)
    if (event.target.className == 'on') {
        oDropdown.children[0].innerHTML = '可用<span class="caret"></span>';
    } else if (event.target.className == 'off') {
        oDropdown.children[0].innerHTML = '不可用<span class="caret"></span>';
    } else {
        oDropdown.children[0].innerHTML = '全部<span class="caret"></span>';
    }
}

// 表格数据渲染===========================================================================================
var data = [
    {
        id: 1,
        warehouseid: "CK001",
        shelfid: "KJ001",
        layers: 100,
        usedlayers: 5,
        records: 1234,
        state: '可用',
        year: 2022,
        founder: "Admin",
        time: "2022-8-23 15:02:27",
    },
    {
        id: 2,
        warehouseid: "CK002",
        shelfid: "KJ002",
        layers: 100,
        usedlayers: 5,
        records: 1234,
        state: '不可用',
        year: 2022,
        founder: "Admin",
        time: "2022-8-23 15:02:27",
    },
    {
        id: 3,
        warehouseid: "CK003",
        shelfid: "KJ003",
        layers: 100,
        usedlayers: 5,
        records: 1234,
        state: '可用',
        year: 2022,
        founder: "Admin",
        time: "2022-8-23 15:02:27",
    },
    {
        id: 4,
        warehouseid: "CK004",
        shelfid: "KJ004",
        layers: 100,
        usedlayers: 5,
        records: 1234,
        state: '可用',
        year: 2022,
        founder: "Admin",
        time: "2022-8-23 15:02:27",
    },
    {
        id: 5,
        warehouseid: "CK005",
        shelfid: "KJ005",
        layers: 100,
        usedlayers: 5,
        records: 1234,
        state: '不可用',
        year: 2022,
        founder: "Admin",
        time: "2022-8-23 15:02:27",
    },
    {
        id: 6,
        warehouseid: "CK006",
        shelfid: "KJ006",
        layers: 100,
        usedlayers: 5,
        records: 1234,
        state: '可用',
        year: 2022,
        founder: "Admin",
        time: "2022-8-23 15:02:27",
    },
    {
        id: 7,
        warehouseid: "CK007",
        shelfid: "KJ007",
        layers: 100,
        usedlayers: 5,
        records: 1234,
        state: '可用',
        year: 2022,
        founder: "Admin",
        time: "2022-8-23 15:02:27",
    },
    {
        id: 8,
        warehouseid: "CK008",
        shelfid: "KJ008",
        layers: 100,
        usedlayers: 5,
        records: 1234,
        state: '可用',
        year: 2022,
        founder: "Admin",
        time: "2022-8-23 15:02:27",
    },
    {
        id: 9,
        warehouseid: "CK009",
        shelfid: "KJ009",
        layers: 100,
        usedlayers: 5,
        records: 1234,
        state: '不可用',
        year: 2022,
        founder: "Admin",
        time: "2022-8-23 15:02:27",
    },
];
// localStorage.setItem("data", JSON.stringify(data));
function render() {
    //查看搜索框的内容
    var str1 = oSearchIdInp.value.trim();//搜索编号的内容
    var str2 = oSearchStateInp.innerText.trim();//搜索状态的内容

    var searchData = []; //最终用来渲染的;
    var data1 = [];

    if (str1 == '') {
        data1 = data;
    } else (
        data1 = data.filter(function (v) {
            return v.warehouseid.includes(str1);
        })
    )

    if (str2 == '全部') {
        searchData = data1;
    } else {
        searchData = data1.filter(function (v) {
            return v.state.startsWith(str2);
        })
    }
    // console.log(data1);
    // console.log(data2);
    // console.log(searchData);
    //让table为空
    oTBody.innerHTML = "";
    //根据count和page准备要渲染的数据
    var renderArr = searchData.slice((page - 1) * count, page * count);
    //循环要渲染的数据
    for (var i = 0; i < renderArr.length; i++) {
        var oTr = document.createElement("tr");
        if (renderArr[i].state == '可用') {
            oTr.innerHTML = `
            <tr>
                <td>${renderArr[i].id}</td>
                <td>${renderArr[i].warehouseid}</td>
                <td>${renderArr[i].shelfid}</td>
                <td>${renderArr[i].layers}</td>
                <td>${renderArr[i].usedlayers}</td>
                <td>${renderArr[i].records}</td>
                <td>
                    <div class="switch-box true">
                        <div class="switch"></div>
                    </div>
                </td>
                <td>${renderArr[i].year}</td>
                <td>${renderArr[i].founder}</td>
                <td>${renderArr[i].time}</td>
                <td><a class="detail">查看</a> <a class="edit">编辑</a> <a class="del">删除</a></td>
            </tr>
        `;
        } else {
            oTr.innerHTML = `
            <tr>
                <td>${renderArr[i].id}</td>
                <td>${renderArr[i].warehouseid}</td>
                <td>${renderArr[i].shelfid}</td>
                <td>${renderArr[i].layers}</td>
                <td>${renderArr[i].usedlayers}</td>
                <td>${renderArr[i].records}</td>
                <td>
                    <div class="switch-box false">
                        <div class="switch"></div>
                    </div>
                </td>
                <td>${renderArr[i].year}</td>
                <td>${renderArr[i].founder}</td>
                <td>${renderArr[i].time}</td>
                <td><a class="detail">查看</a> <a class="edit">编辑</a> <a class="del">删除</a></td>
            </tr>
        `;
        }
        oTBody.appendChild(oTr);
    }

    //渲染页码
    //找到所有的1，2，3，4的页码
    var aPageBtn = document.querySelectorAll(".pageBtn");
    //删除所有的页码
    for (var i = 0; i < aPageBtn.length; i++) {
        oPagination.removeChild(aPageBtn[i].parentNode);
    }
    //根据数据的长度重新创建页码
    for (var i = 1; i <= Math.ceil(searchData.length / count); i++) {
        //创建li
        var oLi = document.createElement("li");
        //给li创建内容
        oLi.innerHTML = `<a class="pageBtn" href="#">${i}</a>`;
        //如果li和当前的页码一致，给他加一个选中的class
        if (i == page) {
            oLi.classList.add("active");
        }
        //在下一页的前面插入页码
        oPagination.insertBefore(oLi, oPagination.lastElementChild);
    }
}
render();

//给分页加事件===========================================================================================
oPagination.addEventListener("click", changePage);
function changePage() {
    //如果当前点击的按钮有pageBtn这个class名字
    if (event.target.className == "pageBtn") {
        //修改全局的page
        page = event.target.innerText;
        //渲染table，渲染分页
        render();
    }
}
//给上一页和下一页加事件
oPrevBtn.addEventListener("click", prev);
oNextBtn.addEventListener("click", next);
function prev() {
    if (page > 1) {
        page--;
        render();
    }
}
function next() {
    if (page < Math.ceil(data.length / count)) {
        page++;
        render();
    }
}

// 删除功能============================================================================================
oTBody.addEventListener("click", del);
function del() {
    if (event.target.className.includes("del")) {
        console.log(event.target);
        //找到id
        var id = event.target.parentNode.parentNode.children[0].innerText;
        //循环数据对比
        for (var i = 0; i < data.length; i++) {
            if (data[i].id == id) {
                //删除id所对应的数据
                data.splice(i, 1);
            }
        }
        //重新渲染
        render();
    }
}

// 修改================================================================================================
oTBody.addEventListener("click", openEdit);
function openEdit() {
    //判断事件源
    if (event.target.className.includes("edit")) {
        //让编辑框显示
        $("#editModal").modal("show");
        //确认是那个id的数据
        var id = event.target.parentNode.parentNode.children[0].innerText;
        //循环数据，找到对应id的，给编辑框赋值
        for (var i = 0; i < data.length; i++) {
            if (data[i].id == id) {
                document.querySelector(".editId").value = data[i].id;
                document.querySelector(".editwarehouseId").value = data[i].warehouseid;
                document.querySelector(".editShelfId").value = data[i].shelfid;
                document.querySelector(".editLayers").value = data[i].layers;
                document.querySelector(".editUsedLayers").value = data[i].usedlayers;
                document.querySelector(".editRecords").value = data[i].records;
                document.querySelector(".editYear").value = data[i].year;
                document.querySelector(".editFounder").value = data[i].founder;
                document.querySelector(".editTime").value = data[i].time;
            }
        }
    }
}

//点击修改保存===========================================================================================
oEditSaveBtn.addEventListener("click", editSave);
function editSave() {
    //看替换的是哪一条；
    var id = document.querySelector(".editId").value;
    //循环数据，找到对应的，更改
    for (var i = 0; i < data.length; i++) {
        if (data[i].id == id) {
            data[i].id = document.querySelector(".editId").value;
            data[i].warehouseid = document.querySelector(".editwarehouseId").value;
            data[i].shelfid = document.querySelector(".editShelfId").value;
            data[i].layers = document.querySelector(".editLayers").value;
            data[i].usedlayers = document.querySelector(".editUsedLayers").value;
            data[i].records = document.querySelector(".editRecords").value;
            data[i].year = document.querySelector(".editYear").value;
            data[i].founder = document.querySelector(".editFounder").value;
            data[i].time = document.querySelector(".editTime").value;
        }
    }
    //关闭弹框
    $("#editModal").modal("hide");
    //重新渲染
    render();
}

// 查看================================================================================================
oTBody.addEventListener("click", openDetail);
function openDetail() {
    //判断事件源
    if (event.target.className.includes("detail")) {
        //让编辑框显示
        $("#detailModal").modal("show");
        //确认是那个id的数据
        var id = event.target.parentNode.parentNode.children[0].innerText;
        //循环数据，找到对应id的，给编辑框赋值
        for (var i = 0; i < data.length; i++) {
            if (data[i].id == id) {
                document.querySelector(".detailId").value = data[i].id;
                document.querySelector(".detailwarehouseId").value = data[i].warehouseid;
                document.querySelector(".detailShelfId").value = data[i].shelfid;
                document.querySelector(".detailLayers").value = data[i].layers;
                document.querySelector(".detailUsedLayers").value = data[i].usedlayers;
                document.querySelector(".detailRecords").value = data[i].records;
                document.querySelector(".detailYear").value = data[i].year;
                document.querySelector(".detailFounder").value = data[i].founder;
                document.querySelector(".detailTime").value = data[i].time;
            }
        }
    }
}

// 修改状态============================================================================================
oTBody.addEventListener("click", changeState);
function changeState() {
    //判断事件源
    if (event.target.className == 'switch') {
        //确认是那个id的数据
        var id = event.target.parentNode.parentNode.parentNode.children[0].innerText;

        if (event.target.parentNode.className.includes('true')) {
            event.target.parentNode.classList.remove('true');
            event.target.parentNode.classList.add('false');

            //循环数据，找到对应id的，给编辑框赋值
            for (var i = 0; i < data.length; i++) {
                if (data[i].id == id) {
                    data[i].state = '不可用';
                }
            }
        } else {
            event.target.parentNode.classList.remove('false');
            event.target.parentNode.classList.add('true');

            //循环数据，找到对应id的，给编辑框赋值
            for (var i = 0; i < data.length; i++) {
                if (data[i].id == id) {
                    data[i].state = '不可用';
                }
            }
        }
    }
}

// 添加==============================================================================================
//添加的时候
oAddSaveBtn.addEventListener('click', addFn);
function addFn() {
    var addId = document.querySelector('.addId').value;
    var addwarehouseId = document.querySelector('.addwarehouseId').value;
    var addShelfId = document.querySelector('.addShelfId').value;
    var addLayers = document.querySelector('.addLayers').value;
    var addUsedLayers = document.querySelector('.addUsedLayers').value;
    var addRecords = document.querySelector('.addRecords').value;
    var addYear = document.querySelector('.addYear').value;
    var addFounder = document.querySelector('.addFounder').value;
    var addTime = document.querySelector('.addTime').value;
    data.push({
        id: addId,
        warehouseid: addwarehouseId,
        shelfid: addShelfId,
        layers: addLayers,
        usedlayers: addUsedLayers,
        records: addRecords,
        state: '可用',
        year: addYear,
        founder: addFounder,
        time: addTime,
    })

    render();
    //让模态框隐藏
    $('#addModal').modal('hide')
}

//点击重置============================================================================================
oResetBtn.addEventListener('click', resetFn);
function resetFn() {
    oSearchIdInp.value = '';
    oSearchStateInp.innerHTML = '全部<span class="caret"></span>';
    render();
}

// 查询===============================================================================================
oSearchBtn.addEventListener('click', searchFn);
function searchFn() {
    page = 1;
    render();
}